package com.ruoyi.web.controller.jpush;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jmessage.api.JMessageClient;
import cn.jmessage.api.common.model.NoDisturbPayload;
import cn.jmessage.api.common.model.RegisterInfo;
import cn.jmessage.api.common.model.UserPayload;
import cn.jmessage.api.common.model.message.MessageBody;
import cn.jmessage.api.common.model.message.MessagePayload;
import cn.jmessage.api.common.model.message.Notification;
import cn.jmessage.api.message.MessageListResult;
import cn.jmessage.api.message.MessageResult;
import cn.jmessage.api.message.MessageType;
import cn.jmessage.api.message.SendMessageResult;
import cn.jmessage.api.resource.DownloadResult;
import cn.jmessage.api.resource.UploadResult;
import cn.jmessage.api.user.UserInfoResult;
import cn.jmessage.api.user.UserListResult;
import cn.jmessage.api.user.UserStateListResult;
import cn.jmessage.api.user.UserStateResult;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.*;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * @version :
 * @program: easyBuy
 * @description: 极光IM封装controller
 * @author: 周爱鸿
 * @create: 2020-09-18 09:46
 **/
@RequestMapping("/im")
@RestController
@Api(tags = "极光IM")
public class IMController extends BaseController {
	@Autowired
	private JMessageClient jMessageClient;

	/**
	 * 用户注册
	 */
	@PostMapping("/register")
	@ApiOperation("用户注册")
	public AjaxResult registerUser(@RequestBody IMUserModel[] users){
		if (StringUtils.isNull(users)){
			return AjaxResult.success("至少添加一个用户");
		}
		String result = "";
		try {

			RegisterInfo[] registerInfos = new RegisterInfo[users.length];
			for (int i = 0 ; i< users.length ; i++) {
				IMUserModel user = users[i];
				registerInfos[i]
						= RegisterInfo.newBuilder()
						.setUsername(user.getUsername())
						.setPassword(user.getPassword())
						.setNickname(user.getNickname())
						.setAvatar(user.getAvatar())
						.setGender(user.getGender())
						.setBirthday(user.getBirthday())
						.setAddress(user.getAddress())
						.setRegion(user.getRegion())
						.setSignature(user.getSignature())
						.build();
			}

			result = jMessageClient.registerUsers(registerInfos);
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success(result);
	}

	/**
	 * 获取用户信息
	 */
	@GetMapping("getUserInfo")
	@ApiOperation("获取用户信息")
	public AjaxResult getUserInfo(String username){
		UserInfoResult userInfo = null;
		try {
			userInfo = jMessageClient.getUserInfo(username);
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success(userInfo);
	}

	/**
	 * 管理员注册
	 */
	@GetMapping("/admin/register")
	@ApiOperation("管理员注册")
	public AjaxResult registerAdmin(String username , String password){
		String result = null;
		try {
			result = jMessageClient.registerAdmins(username, password);
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success(result);
	}

	/**
	 * 获取管理员列表
	 */
	@GetMapping("/adminslist")
	@ApiOperation("获取管理员列表")
	public AjaxResult adminslist(){
		String result = null;
		try {
			PageDomain pageDomain = TableSupport.getPageDomain();
			result = jMessageClient.registerAdmins(pageDomain.getPageNum()+"", pageDomain.getPageSize()+"");
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success(result);
	}

	/**
	 * 更新用户信息
	 */
	@GetMapping("/updateUserInfo")
	@ApiOperation("更新用户信息")
	public AjaxResult updateUserInfo(IMUserModel user){
		try {
			UserPayload userPayload = UserPayload.newBuilder()
					.setNickname(user.getNickname())
					.setAvatar(user.getAvatar())
					.setAddress(user.getAddress())
					.setBirthday(user.getBirthday())
					.setRegion(user.getRegion())
					.setSignature(user.getSignature())
					.setGender(user.getGender())
					.build();
			jMessageClient.updateUserInfo(user.getUsername(),userPayload);
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success("修改成功");
	}

	/**
	 * 单个用户在线状态
	 */
	@GetMapping("/{username}/userstat")
	@ApiOperation("单个用户在线状态")
	public AjaxResult userstat(@PathVariable String username){
		UserStateResult userState = null ;
		try {
			 userState = jMessageClient.getUserState(username);
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success(userState);
	}
	/**
	 * 批量用户在线状态
	 */
	@GetMapping("/users/userstat")
	@ApiOperation("批量用户在线状态")
	public AjaxResult usersStat(String... usernames){
		UserStateListResult[] userState = null ;
		try {
			 userState = jMessageClient.getUsersState(usernames);
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success(userState);
	}

	/**
	 * 修改密码
	 */
	@GetMapping("/{username}/password")
	@ApiOperation("修改密码")
	public AjaxResult usersStat(@PathVariable String username,String password){
		try {
			 jMessageClient.updateUserPassword(username,password);
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success("密码修改成功");
	}

	/**
	 * 删除单个用户
	 */
	@DeleteMapping("/{username}")
	@ApiOperation("删除单个用户")
	public AjaxResult delete(@PathVariable String username){
		try {
			 jMessageClient.deleteUser(username);
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success("删除用户" + username + "成功");
	}


	/**
	 * 批量删除用户
	 */
	@DeleteMapping("/users")
	@ApiOperation("批量删除用户")
	public AjaxResult delete( String... usernames){
		try {
			for (String username : usernames) {
				jMessageClient.deleteUser(username);

			}
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success("删除成功");
	}

	/**
	 * 添加黑名单
	 */
	@GetMapping("/{username}/blacklist")
	@ApiOperation("添加黑名单")
	public AjaxResult blacklist( @PathVariable String  username , String... usernames){
		ResponseWrapper responseWrapper = null ;
		try {
			responseWrapper = jMessageClient.addBlackList(username, usernames);
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success(responseWrapper);
	}

	/**
	 * 移除黑名单
	 */
	@GetMapping("/{username}/removeBlacklist")
	@ApiOperation("移除黑名单")
	public AjaxResult removeBlacklist( @PathVariable String  username , String... usernames){
		ResponseWrapper responseWrapper = null ;
		try {
			responseWrapper = jMessageClient.removeBlacklist(username, usernames);
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success(responseWrapper);
	}

	/**
	 * 黑名单列表
	 */
	@GetMapping("/blacklist")
	@ApiOperation("黑名单列表")
	public AjaxResult blacklist( String  username){
		UserInfoResult[] userInfoResults = null ;
		try {
			userInfoResults = jMessageClient.getBlackList(username);
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success(userInfoResults);
	}
	/**
	 * 用户列表
	 */
	@GetMapping("/userlist")
	@ApiOperation("用户列表")
	public AjaxResult userlist(){
		UserListResult userInfoResults = null ;
		try {
			PageDomain pageDomain = TableSupport.getPageDomain();
			userInfoResults = jMessageClient.getUserList(pageDomain.getPageNum(),pageDomain.getPageSize());
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success(userInfoResults);
	}

	/**
	 * 免打扰设置
	 */
	@PostMapping("/{username}/nodisturb")
	@ApiOperation("免打扰设置")
	public AjaxResult nodisturb(@PathVariable String username, @RequestBody IMNodisturbModel model){
		ResponseWrapper responseWrapper = null ;
		try {
			NoDisturbPayload payload = new NoDisturbPayload.Builder()
					.setGlobal(model.getGlobal())
					.setAddGroupIds(model.getAddGroupIds())
					.setRemoveGroupIds(model.getRemoveGroupIds())
					.setAddSingleUsers(model.getAddSingleUsers())
					.setAddSingleUsers(model.getRemoveSingleUsers())
					.build();
			 responseWrapper = jMessageClient.setNoDisturb(username, payload);
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success(responseWrapper);
	}

	/**
	 * 禁用用户
	 * disable: true代表禁用用户，false代表激活用户
	 */
	@GetMapping("/{username}/forbidden")
	@ApiOperation("禁用用户")
	public AjaxResult forbidden(@PathVariable String username,boolean disable){
		ResponseWrapper responseWrapper = null ;
		try {

			 responseWrapper = jMessageClient.forbidUser(username, disable);
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success(responseWrapper);
	}

	/**
	 * 发送文本消息
	 */
	@PostMapping("/text/messages")
	@ApiOperation("发送文本消息")
	public AjaxResult textMessages( @RequestBody IMTextMessageModel textMessageModel){
		SendMessageResult sendMessageResult = null ;
		try {

			sendMessageResult = jMessageClient.sendMessage( MessagePayload.newBuilder()
					.setMessageBody(MessageBody.newBuilder()
							.setText(textMessageModel.getMessageBody().getText())
							.build())
					.setFromId(textMessageModel.getFromId())
					.setFromName(textMessageModel.getFromName())
					.setFromType(textMessageModel.getFromType())
					.setMessageType(MessageType.TEXT)
					.setNoNotification(textMessageModel.getNoNotification())
					.setNoOffline(textMessageModel.getNoOffline())
					.setNotification(Notification.newBuilder()
							.setAlert(textMessageModel.getNotification().getAlert())
							.setTitle(textMessageModel.getNotification().getTitle())
							.build())
					//不进行跨应用消息发送
					//.setTargetAppKey(textMessageModel.getTargetAppkey())
					.setTargetId(textMessageModel.getTargetId())
					.setTargetName(textMessageModel.getTargetName())
					.setTargetType(textMessageModel.getTargetType())
					.setVersion(textMessageModel.getVersion())
					.build());
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success(sendMessageResult);
	}


	/**
	 * 发送图片消息
	 */
	@PostMapping("/image/messages")
	@ApiOperation("发送图片消息")
	public AjaxResult imageMessages( @RequestBody IMImageMessageModel imImageMessageModel){
		SendMessageResult sendMessageResult = null ;
		try {

			sendMessageResult = jMessageClient.sendMessage( MessagePayload.newBuilder()
					.setMessageBody(MessageBody.newBuilder()
							.setMediaId(imImageMessageModel.getMessageBody().getMediaId())
							.setMediaCrc32(imImageMessageModel.getMessageBody().getMediaCrc32())
							.setWidth(imImageMessageModel.getMessageBody().getWidth())
							.setHeight(imImageMessageModel.getMessageBody().getHeight())
							.setFormat(imImageMessageModel.getMessageBody().getFormat())
							.setHash(imImageMessageModel.getMessageBody().getHash())
							.setFsize(imImageMessageModel.getMessageBody().getFsize())
							.build())
					.setFromId(imImageMessageModel.getFromId())
					.setFromName(imImageMessageModel.getFromName())
					.setFromType(imImageMessageModel.getFromType())
					.setMessageType(MessageType.IMAGE)
					.setNoNotification(imImageMessageModel.getNoNotification())
					.setNoOffline(imImageMessageModel.getNoOffline())
					.setNotification(Notification.newBuilder()
							.setAlert(imImageMessageModel.getNotification().getAlert())
							.setTitle(imImageMessageModel.getNotification().getTitle())
							.build())
					//不进行跨应用消息发送
				//	.setTargetAppKey(imImageMessageModel.getTargetAppkey())
					.setTargetId(imImageMessageModel.getTargetId())
					.setTargetName(imImageMessageModel.getTargetName())
					.setTargetType(imImageMessageModel.getTargetType())
					.setVersion(imImageMessageModel.getVersion())
					.build());
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success(sendMessageResult);
	}

	/**
	 * 发送语音消息
	 */
	@PostMapping("/voice/messages")
	@ApiOperation("发送语音消息")
	public AjaxResult voiceMessages( @RequestBody IMVoiceMessageModel imVoiceMessageModel){
		SendMessageResult sendMessageResult = null ;
		try {

			sendMessageResult = jMessageClient.sendMessage( MessagePayload.newBuilder()
					.setMessageBody(MessageBody.newBuilder()
							.setMediaId(imVoiceMessageModel.getMessageBody().getMediaId())
							.setMediaCrc32(imVoiceMessageModel.getMessageBody().getMediaCrc32())
							.setDuration(imVoiceMessageModel.getMessageBody().getDuration())
							.setHash(imVoiceMessageModel.getMessageBody().getHash())
							.setFsize(imVoiceMessageModel.getMessageBody().getFsize())
							.build())
					.setFromId(imVoiceMessageModel.getFromId())
					.setFromName(imVoiceMessageModel.getFromName())
					.setFromType(imVoiceMessageModel.getFromType())
					.setMessageType(MessageType.IMAGE)
					.setNoNotification(imVoiceMessageModel.getNoNotification())
					.setNoOffline(imVoiceMessageModel.getNoOffline())
					.setNotification(Notification.newBuilder()
							.setAlert(imVoiceMessageModel.getNotification().getAlert())
							.setTitle(imVoiceMessageModel.getNotification().getTitle())
							.build())
					//不进行跨应用消息发送
				//	.setTargetAppKey(imVoiceMessageModel.getTargetAppkey())
					.setTargetId(imVoiceMessageModel.getTargetId())
					.setTargetName(imVoiceMessageModel.getTargetName())
					.setTargetType(imVoiceMessageModel.getTargetType())
					.setVersion(imVoiceMessageModel.getVersion())
					.build());
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success(sendMessageResult);
	}


	/**
	 * 消息撤回
	 */
	@GetMapping("/{username}/{msgid}/retract")
	@ApiOperation("消息撤回")
	public AjaxResult retract(@PathVariable String username , @PathVariable Long msgid){
		ResponseWrapper responseWrapper = null ;
		try {
			 responseWrapper = jMessageClient.retractMessage(username, msgid);
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success(responseWrapper);
	}

	/**
	 * 文件下载
	 */
	@GetMapping("/resource/download/{mediaId}")
	@ApiOperation("文件下载")
	public AjaxResult resourcedownload(@PathVariable String mediaId){
		DownloadResult downloadResult = null ;
		try {
			downloadResult = jMessageClient.downloadFile(mediaId);
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success(downloadResult);
	}


	/**
	 * 文件上传
	 */
	@GetMapping("/resource/upload")
	@ApiOperation("文件上传")
	@ApiImplicitParam(name = "类型", value = "文件类型 支持是image, file, voice",required = true)
	public AjaxResult resourceupload(String fileurl , String type){
		if (!fileurl.contains("profile")){
			return AjaxResult.error("文件url有误,请上传正确的图片url");
		}
		// url 转换成本地绝对路径
		fileurl = RuoYiConfig.getProfile() + fileurl.substring(fileurl.indexOf(Constants.RESOURCE_PREFIX)+Constants.RESOURCE_PREFIX.length());
		UploadResult uploadResult = null ;
		try {
			uploadResult = jMessageClient.uploadFile(fileurl,type);
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success(uploadResult);
	}
	/**
	 * 消息接收
	 */
	@GetMapping("/message")
	@ApiOperation("消息接收")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "postusername",value = "消息发送者用户名",required = true),
			@ApiImplicitParam(name = "reciverusernamenpm",value = "消息接收者用户名",required = true)
	})
	public AjaxResult getMessage( String postusername ){
		MessageListResult result = null;
		try {
			// 接收近七天的1000条消息
			result = jMessageClient.getUserMessages(postusername, 1000
					, DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",DateUtils.getLater(DateUtils.getNowDate(),-7, Calendar.DATE))
					,DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",DateUtils.getNowDate()));
		} catch (APIConnectionException e) {
			e.printStackTrace();
		} catch (APIRequestException e) {
			e.printStackTrace();
		}
		return AjaxResult.success(result);
	}




}
